package com.sikadwafastdaisfondturbo.pretloan.ui.process.page

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageOcrDriverLicenseBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.CameraOcrActivity
import com.sikadwafastdaisfondturbo.pretloan.ui.process.activity.ProcessActivity
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.PhotoDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.gilde.ImageUtil
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.imagecovert.ImageConvert
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/19 18:22
 * @Annotation：流程 - 证件照 - 驾驶证信息
 */
class OcrDriverLicensePage: ProFragment() {

    lateinit var binding: PageOcrDriverLicenseBinding
    private var isFront = false//是否是正面
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageOcrDriverLicenseBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                HHLog.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        if (isFront){
                            ImageUtil.instance!!.loadImageUrl(context,binding.imgFront,localPath)
                        } else {
                            ImageUtil.instance!!.loadImageUrl(context,binding.imgBack,localPath)
                        }
                        uploadImageAction(localPath)
                    }
                }


            } else {
                HHLog.e("No media selected")
            }
        }
    }

    override fun initListener() {
        //驾驶证正面
        binding.frontLayout.setOnClickListener {
//            if (imgFrontUrl .isNotEmpty()){
//                return@setOnClickListener
//            }
            isFront = true
            showPhotoDialog("DriverLicense Front")
        }

        //驾驶证反面
        binding.backLayout.setOnClickListener {
//            if (imgBackUrl.isNotEmpty()){
//                return@setOnClickListener
//            }
            isFront = false
            showPhotoDialog("DriverLicense Back")
        }
        //下一步
        binding.btnNext.setOnClickListener {
            if (imgFrontUrl.isEmpty() || imgBackUrl.isEmpty()){
                showToast(getString(R.string.tips_submit_error))
                return@setOnClickListener
            }

            val params = JSONObject().addCommonParams().apply {
                put("path", AppUrls.PATH.OCR_INFO)
                put("cardType","DRIVING")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
                put("cardImgUrl",imgFrontUrl)//证件图片正面
                put("cardBackImgUrl",imgBackUrl)//证件图片反面
            }
            val act = context as ProcessActivity
            act.submitAction(params)
            addEvent(EventType.CLICK.CLICK_STEP_OCR_DRIVERLICENSE_NEXT,"")
        }
    }

    override fun initData() {
    }

    /**
     * 相机、相册选择
     */
    private fun showPhotoDialog(eventRemark: String){
        val photoDialog = PhotoDialog(context,eventRemark,object : PhotoDialog.IDialogCallback{
            override fun openCamera() {
                addEvent(EventType.CLICK.CLICK_CAMERA,eventRemark)
                onOpenCamera()
            }
            override fun openAlbum() {
                addEvent(EventType.CLICK.CLICK_ALBUM,eventRemark)
                onOpenAlbum()
            }
        })
        photoDialog.show()
    }

    /**
     * 拍照
     */
    private val takePhotoResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                HHLog.e(">>>>>>onActivityResult: data = " + result.data)
                val imgPath = result.data!!.getStringExtra("imgLocalPath")
                if (imgPath != null){
                    if (isFront){
                        ImageUtil.instance!!.loadImageUrl(context,binding.imgFront,imgPath)
                    } else {
                        ImageUtil.instance!!.loadImageUrl(context,binding.imgBack,imgPath)
                    }
                    uploadImageAction(imgPath)
                }
            }
        }
    }

    /**
     * 打开相机
     */
    private fun onOpenCamera(){
        val intent = Intent(context, CameraOcrActivity::class.java)
        takePhotoResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun onOpenAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 根据uri获取文件路径
     */
    private fun getRealPathFromURI(contentURI: Uri): String? {
        val result: String?
        val cursor = requireContext().contentResolver.query(contentURI, null, null, null, null)
        if (cursor == null) {
            result = contentURI.path
        } else {
            cursor.moveToFirst()
            val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
            result = cursor.getString(idx)
            cursor.close()
        }
        return result
    }

    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl, File(imgPath),object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val imgUrl = data.optJSONObject("obj")!!.optString("url")
                if (isFront){
                    imgFrontUrl = imgUrl
                    addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "DriverLicense Front ：$imgUrl")
                } else {
                    imgBackUrl = imgUrl
                    addEvent(EventType.CLICK.CLICK_STEP_OCR_UPLOAD_USE_PHOTO, "DriverLicense Back ：$imgUrl")
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_START,"DriverLicense"),"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(String.format(EventType.PAGE.PAGE_STEP_OCR_XX_END,"DriverLicense"),"")
    }
}